import React from 'react';
import { Result, Button, Card, Typography, Space, Alert } from 'antd';
import { BugOutlined, ReloadOutlined, HomeOutlined } from '@ant-design/icons';
import errorMonitor from './errorMonitor';

const { Paragraph, Text } = Typography;

/**
 * React错误边界组件
 * 用于捕获React组件树中的JavaScript错误
 */
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null,
      errorId: null
    };
  }

  static getDerivedStateFromError(error) {
    // 更新state，下次渲染将显示错误UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息
    const errorId = Date.now() + Math.random();
    
    this.setState({
      error,
      errorInfo,
      errorId
    });

    // 使用错误监控服务记录错误
    errorMonitor.logError(
      `React组件错误: ${error.message}`,
      {
        ...error,
        componentStack: errorInfo.componentStack,
        errorBoundary: this.constructor.name
      }
    );

    // 控制台输出详细错误信息
    console.group('🚨 React错误边界捕获到错误');
    console.error('错误:', error);
    console.error('错误信息:', errorInfo);
    console.error('组件堆栈:', errorInfo.componentStack);
    console.groupEnd();
  }

  handleReload = () => {
    window.location.reload();
  };

  handleGoHome = () => {
    window.location.href = '/';
  };

  handleRetry = () => {
    this.setState({
      hasError: false,
      error: null,
      errorInfo: null,
      errorId: null
    });
  };

  render() {
    if (this.state.hasError) {
      const isDevelopment = process.env.NODE_ENV === 'development';
      
      return (
        <div style={{ 
          padding: '20px', 
          minHeight: '100vh', 
          background: '#f5f5f5',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <Card style={{ maxWidth: 600, width: '100%' }}>
            <Result
              status="error"
              icon={<BugOutlined style={{ color: '#ff4d4f' }} />}
              title="页面出现错误"
              subTitle={
                isDevelopment 
                  ? "开发环境下显示详细错误信息，生产环境将显示友好提示"
                  : "抱歉，页面遇到了一些问题，请尝试刷新页面或返回首页"
              }
              extra={
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space wrap>
                    <Button type="primary" icon={<ReloadOutlined />} onClick={this.handleReload}>
                      刷新页面
                    </Button>
                    <Button icon={<HomeOutlined />} onClick={this.handleGoHome}>
                      返回首页
                    </Button>
                    <Button onClick={this.handleRetry}>
                      重试
                    </Button>
                  </Space>
                  
                  {isDevelopment && (
                    <Alert
                      message="开发环境错误信息"
                      description={
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <div>
                            <Text strong>错误ID:</Text> {this.state.errorId}
                          </div>
                          <div>
                            <Text strong>错误消息:</Text> {this.state.error?.message}
                          </div>
                          <div>
                            <Text strong>错误堆栈:</Text>
                            <Paragraph 
                              code 
                              style={{ 
                                background: '#f6f8fa', 
                                padding: '8px',
                                fontSize: '12px',
                                maxHeight: '200px',
                                overflow: 'auto'
                              }}
                            >
                              {this.state.error?.stack}
                            </Paragraph>
                          </div>
                          {this.state.errorInfo?.componentStack && (
                            <div>
                              <Text strong>组件堆栈:</Text>
                              <Paragraph 
                                code 
                                style={{ 
                                  background: '#f6f8fa', 
                                  padding: '8px',
                                  fontSize: '12px',
                                  maxHeight: '150px',
                                  overflow: 'auto'
                                }}
                              >
                                {this.state.errorInfo.componentStack}
                              </Paragraph>
                            </div>
                          )}
                        </Space>
                      }
                      type="error"
                      showIcon
                      style={{ textAlign: 'left', marginTop: '16px' }}
                    />
                  )}
                </Space>
              }
            />
          </Card>
        </div>
      );
    }

    return this.props.children;
  }
}

/**
 * 高阶组件：为组件添加错误边界
 */
export const withErrorBoundary = (WrappedComponent, errorBoundaryProps = {}) => {
  const WithErrorBoundaryComponent = (props) => (
    <ErrorBoundary {...errorBoundaryProps}>
      <WrappedComponent {...props} />
    </ErrorBoundary>
  );
  
  WithErrorBoundaryComponent.displayName = `withErrorBoundary(${WrappedComponent.displayName || WrappedComponent.name})`;
  
  return WithErrorBoundaryComponent;
};

/**
 * Hook：在函数组件中使用错误处理
 */
export const useErrorHandler = () => {
  const handleError = React.useCallback((error, errorInfo = {}) => {
    errorMonitor.logError(
      error.message || '未知错误',
      {
        ...error,
        ...errorInfo,
        source: 'useErrorHandler'
      }
    );
  }, []);

  return handleError;
};

export default ErrorBoundary;